package com.diyunapp.xilinapp.adapters;

import android.content.Context;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.BuyCarGoodsInBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.BuyCarGoodsInfoChageInterface;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/6/21.
 */
public class BuyCarInnerAdapter extends BaseAdapter implements View.OnClickListener {

    private List<BuyCarGoodsInBean> myLists;
    private Context myContext;
    private BuyCarGoodsInfoChageInterface goodsChangeIf;

    public BuyCarInnerAdapter(List<BuyCarGoodsInBean> myLists, Context myContext, BuyCarGoodsInfoChageInterface goodsChangeIf) {
        this.myLists = myLists;
        this.myContext = myContext;
        this.goodsChangeIf = goodsChangeIf;
    }

    @Override
    public int getCount() {
        return myLists.size();
    }

    @Override
    public Object getItem(int position) {
        return myLists.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(myContext).inflate(R.layout.buycar_inner_list, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final BuyCarGoodsInBean data = myLists.get(position);
        if (data.isGoodSelected()) {
            holder.goodSelectCb.setChecked(true);
        } else {
            holder.goodSelectCb.setChecked(false);
        }

        if(data.isDeleteState())
        {
            holder.buycarDeleteallTv.setVisibility(View.VISIBLE);
        }
        else
        {
            holder.buycarDeleteallTv.setVisibility(View.GONE);
        }

        final int deletePos = FormatConfirm.stringToInt(data.getCart_id());
        holder.buycarDeleteallTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goodsChangeIf.changeGoodsNum(4, deletePos);
            }
        });

        holder.goodSelectCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                data.setGoodSelected(isChecked);
                if (isChecked) {
                    goodsChangeIf.changeGoodsNum(1, 1);
                } else {
                    goodsChangeIf.changeGoodsNum(2, 1);
                }
            }
        });

        Log.i("zhangxiaoxidebug", "goods info-------------position = " + position);
        ImageLoader.getInstance().displayImage(data.getGoodImg(), holder.incarGoodImg, FormatConfirm.getOption());
        holder.incarGoodnameTv.setText(data.getGoodName());
        holder.incarGoodPriceTv.setText("￥" + data.getGoodPrice());
        holder.incargoodMakretPriceTv.setText("￥" + data.getMarketPrice());
        //设置中划线
        holder.incargoodMakretPriceTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        holder.incargoodParamsTv.setText(data.getGoodParams());

        holder.incarIncressnumBt.setOnClickListener(this);
        holder.incarNumsetEt.setText(String.valueOf(data.getTotalGoodNum()));
        holder.incarNumsetEt.setTag(position);
        holder.incarIncressnumBt.setTag(holder.incarNumsetEt);
        holder.incarDecressnumBt.setOnClickListener(this);
        holder.incarDecressnumBt.setTag(holder.incarNumsetEt);
        return convertView;
    }

    @Override
    public void onClick(View v) {
        EditText myEdit = (EditText) v.getTag();
        int position = FormatConfirm.stringToInt(myEdit.getTag().toString());
        int nowNum = myLists.get(position).getTotalGoodNum();
        switch (v.getId()) {
            case R.id.incar_incressnum_bt:
                nowNum++;
                v.setClickable(false);
                Toast.makeText(myContext,"数量修改中...",Toast.LENGTH_SHORT).show();
                changeBuycarNums(v,myLists.get(position).getCart_id(),String.valueOf(nowNum));
                myLists.get(position).setTotalGoodNum(nowNum);
                myEdit.setText(String.valueOf(nowNum));
                //如果当前商品处于选中状态，才去通知店铺进行数量修改，否则仅更新界面
                if (myLists.get(position).isGoodSelected()) {
                    goodsChangeIf.changeGoodsNum(3, nowNum);
                }
                break;
            case R.id.incar_decressnum_bt:
                if (nowNum > 1) {
                    nowNum--;
                    Toast.makeText(myContext,"数量修改中...",Toast.LENGTH_SHORT).show();
                    changeBuycarNums(v,myLists.get(position).getCart_id(),String.valueOf(nowNum));
                    myLists.get(position).setTotalGoodNum(nowNum);
                    myEdit.setText(String.valueOf(nowNum));
                    //如果当前商品处于选中状态，才去通知店铺进行数量修改，否则仅更新界面
                    if (myLists.get(position).isGoodSelected()) {
                        goodsChangeIf.changeGoodsNum(3, nowNum);
                    }
                }
                break;
            default:
                break;
        }

    }

    static class ViewHolder {
        @Bind(R.id.good_select_cb)
        CheckBox goodSelectCb;
        @Bind(R.id.incar_good_img)
        ImageView incarGoodImg;
        @Bind(R.id.incar_goodname_tv)
        TextView incarGoodnameTv;
        @Bind(R.id.incar_good_price_tv)
        TextView incarGoodPriceTv;
        @Bind(R.id.incargood_makret_price_tv)
        TextView incargoodMakretPriceTv;
        @Bind(R.id.incargood_params_tv)
        TextView incargoodParamsTv;
        @Bind(R.id.incar_incressnum_bt)
        Button incarIncressnumBt;
        @Bind(R.id.incar_numset_et)
        EditText incarNumsetEt;
        @Bind(R.id.incar_decressnum_bt)
        Button incarDecressnumBt;
        @Bind(R.id.buycar_deleteall_tv)
        TextView buycarDeleteallTv;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    //修改购物车商品数量
    private void changeBuycarNums(final View theView,String carid,String num) {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_cart&op=cart_edit_quantity";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", MainActivity.myLogin.getLoginkey());
        params.addBodyParameter("cart_id", carid);
        params.addBodyParameter("quantity", num);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "content_result=" + result);
                        theView.setClickable(true);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(myContext,"购物车数量修改失败，请检查您的网络！",Toast.LENGTH_LONG).show();
                            }
                            else
                            {
                                Log.i("zhangxiaoxidebug", "购物车数量修改成功！" );
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "购物车数量修改失败！" + msg);
                        Toast.makeText(myContext,msg,Toast.LENGTH_LONG).show();
                    }
                }
        );
    }
}
